from django.db import models
from django.urls import reverse

# Create your models here.


class Category(models.Model):
    name = models.CharField(max_length=200,db_index=True, verbose_name='名称')
    slug = models.SlugField(max_length=200, db_index=True,  unique=True, verbose_name='分类标签')

    class Meta:
        ordering = ('name',)
        verbose_name = "类别"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category',
                       args=[self.slug])


class Product(models.Model):
    category = models.ForeignKey(Category,related_name='products_category', on_delete=models.CASCADE, verbose_name='分类')
    name = models.CharField(max_length=200, db_index=True, verbose_name='名字')
    slug = models.SlugField(max_length=200, db_index=True, verbose_name='产品标签')
    image = models.ImageField(upload_to='products/%Y/%m/%d',blank=True, verbose_name='图片')
    description = models.TextField(blank=True, verbose_name='描述')
    """
     # max_digits 属性可用于设定数字的最大值，decimal_places 属性用于设置小数位数。
    """
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='价格')
    stock = models.PositiveIntegerField(verbose_name='库存')
    available = models.BooleanField(default=True, verbose_name='是否正常')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)
        verbose_name = "产品"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_detail',
                       args=[self.id, self.slug])
